package com.rongshu.sendmessage.util.addimage;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.widget.Toast;

import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;

import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.util.StringUtils;

import java.io.File;

/**
 * Created by cxf on 2018/9/29.
 * 选择图片 裁剪
 */

public class ProcessImageUtil extends ProcessResultUtil {

    private static final String CROP_IMAGE_FILE_NAME = "bala_crop.jpg";
    private Context mContext;
    private String[] mCameraPermissions;
    private String[] mAlumbPermissions;
    private Runnable mCameraPermissionCallback;
    private Runnable mAlumbPermissionCallback;
    private ActivityResultCallback mCameraResultCallback;
    private ActivityResultCallback mAlumbResultCallback;
    private ActivityResultCallback mCropResultCallback;
    private File mCameraResult;//拍照后得到的图片
    private File mCorpResult;//裁剪后得到的图片
    private ImageResultCallback mResultCallback;
    private boolean mNeedCrop;//是否需要裁剪

    public ProcessImageUtil(FragmentActivity activity) {
        super(activity);
        mContext = activity;
        mCameraPermissions = new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
        };
        mAlumbPermissions = new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
        };
        mCameraPermissionCallback = new Runnable() {
            @Override
            public void run() {
                takePhoto();
            }
        };
        mAlumbPermissionCallback = new Runnable() {
            @Override
            public void run() {
                chooseFile();
            }
        };
        mCameraResultCallback = new ActivityResultCallback() {
            @Override
            public void onSuccess(Intent intent) {
                if (mResultCallback != null) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {//
                        // Android 10 使用图片uri加载
                        String[] filePathColumn = {MediaStore.Images.Media.DATA};
                        Cursor cursor = ((Activity)mContext).getContentResolver().query(uri,
                                filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        String path = cursor.getString(columnIndex);  //获取照片路径
                        File f = new File(path);
                        mResultCallback.onSuccess(f,uri);
                    } else {
                        // 使用图片路径加载
                        mResultCallback.onSuccess(mCameraResult,uri);
                    }

                }
            }
            @Override
            public void onFailure() {
                Toast.makeText(mContext, R.string.img_camera_cancel, Toast.LENGTH_SHORT).show();
            }
        };
        mAlumbResultCallback = new ActivityResultCallback() {
            @Override
            public void onSuccess(Intent intent) {
//                if (mNeedCrop) {
//                    crop(intent.getData());
//                    return;
//                }
                if (mResultCallback != null) {
                    Uri selectedImage = intent.getData(); //获取系统返回的照片的Uri
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = ((Activity)mContext).getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String path = cursor.getString(columnIndex);  //获取照片路径
                    File f = new File(path);
                    mResultCallback.onSuccess(f,selectedImage);
                }
            }

            @Override
            public void onFailure() {
                Toast.makeText(mContext, R.string.img_alumb_cancel, Toast.LENGTH_SHORT).show();
            }
        };

        mCropResultCallback = new ActivityResultCallback() {
            @Override
            public void onSuccess(Intent intent) {
                if (mResultCallback != null) {
                    mResultCallback.onSuccess(mCorpResult);
                }
            }

            @Override
            public void onFailure() {

                Toast.makeText(mContext, R.string.img_crop_cancel, Toast.LENGTH_SHORT).show();
            }
        };
    }
    /**
     * 拍照获取图片
     */
    public void getImageByCamera(boolean needCrop) {
        mNeedCrop = needCrop;
        requestPermissions(mCameraPermissions, mCameraPermissionCallback);
    }

    /**
     * 拍照获取图片
     */
    public void getImageByCamera() {
        getImageByCamera(true);
    }

    /**
     * 相册获取图片
     */
    public void getImageByAlumb() {
        mNeedCrop = true;
        requestPermissions(mAlumbPermissions, mAlumbPermissionCallback);
    }


    /**
     * 开启摄像头，执行照相
     */
    private Uri uri;
    private void takePhoto() {
        if (mResultCallback != null) {
            mResultCallback.beforeCamera();
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mCameraResult = StringUtils.getNewFile(mContext,"yizhongxin.jpg");

        if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){//android10的版本
            uri = StringUtils.createImageUri(mContext);
        }else
            if (Build.VERSION.SDK_INT >= 24) {//&&Build.VERSION.SDK_INT<android.os.Build.VERSION_CODES.Q
            uri = FileProvider.getUriForFile(mContext, mContext.getPackageName()+".fileImageProvider", mCameraResult);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(mCameraResult);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        startActivityForResult(intent, mCameraResultCallback);
    }



    /**
     * 打开相册，选择文件
     */
    private void chooseFile() {
        Intent intent1 = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//        Intent intent = new Intent();
//        intent.addCategory(Intent.CATEGORY_OPENABLE);
//        intent.setType("image/*");
//        if (Build.VERSION.SDK_INT < 19) {
//            intent.setAction(Intent.ACTION_GET_CONTENT);
//        } else {
//            intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
//        }
        startActivityForResult(intent1, mAlumbResultCallback);
    }
//    private File getNewFile() {
//        // 裁剪头像的绝对路径
//        File dir = new File(AppConfig.CAMERA_IMAGE_PATH);
//        if (!dir.exists()) {
//            dir.mkdirs();
//        }
//        return new File(dir, DateFormatUtil.getCurTimeString() + ".png");
//    }
    /**
     * 裁剪
     */
//    private void crop(Uri inputUri) {
//        mCorpResult = StringUtils.getNewFile(mContext,"caijian.png");
//        try {
//            Uri resultUri;
//            if (Build.VERSION.SDK_INT >= 24) {
//                //mContext, mContext.getPackageName()+".fileImageProvider", mCameraResult
//                resultUri = FileProvider.getUriForFile(mContext,  mContext.getPackageName()+".fileImageProvider", mCorpResult);
//            } else {
//                resultUri = Uri.fromFile(mCorpResult);
//            }
//
//            if (resultUri == null || mFragment == null || mContext == null) {
//                return;
//            }
//            Intent intent = new Intent("com.android.camera.action.CROP");
////设置源地址uri
//            intent.setDataAndType(inputUri, "image/*");
//            intent.putExtra("crop", "true");
//            intent.putExtra("aspectX", 1);
//            intent.putExtra("aspectY", 1);
//            intent.putExtra("outputX", 200);
//            intent.putExtra("outputY", 200);
//            intent.putExtra("scale", true);
////设置目的地址uri
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, resultUri);
////设置图片格式
//            intent.putExtra("outputFormat", Bitmap.CompressFormat.WEBP.toString());
//            intent.putExtra("return-data", false);
//            intent.putExtra("noFaceDetection", true); // no face detection
//            startActivityForResult(intent, mCropResultCallback);
//
////            UCrop uCrop = UCrop.of(inputUri, resultUri)
////                    .withAspectRatio(1, 1)
////                    .withMaxResultSize(400, 400);
////            Intent intent = uCrop.getIntent(mContext);
////            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
////            startActivityForResult(intent, mCropResultCallback);
//        } catch (Exception e) {
//            try {
////                UCropActivity
//                Uri resultUri = FileProvider.getUriForFile(mContext,mContext.getPackageName()+".fileImageProvider", mCorpResult);
//                if (resultUri == null || mFragment == null || mContext == null) {
//                    return;
//                }
//                UCrop uCrop = UCrop.of(inputUri, resultUri)
//                        .withAspectRatio(1, 1)
//                        .withMaxResultSize(400, 400);
//                Intent intent = uCrop.getIntent(mContext);
//                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//                startActivityForResult(intent, mCropResultCallback);
//            } catch (Exception e1) {
//                e1.printStackTrace();
//            }
//        }
//    }


    public void setImageResultCallback(ImageResultCallback resultCallback) {
        mResultCallback = resultCallback;
    }

    @Override
    public void release() {
        super.release();
        mResultCallback = null;
    }
}
